import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:zrjz/comm/engine/camera_engine.dart';
import 'package:zrjz/comm/service/config.dart';
import 'package:zrjz/comm/utils/device_utils.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/widget/dialog/app_default_dialog.dart';
import 'package:zrjz/comm/widget/dialog/permission_desc_dialog.dart';

import '../engine/album_engine.dart';
import '../engine/image_crop_engine.dart';
import '../widget/dialog/album_default_select_dialog.dart';

/*
    相机相册选择的封装
    1.相机相册的选择弹框
    2.相机相册权限提示详情描述弹窗
    3.调用相机相册的引擎封装类 CameraEngine  AlbumEngine  ImageCropEngine 的使用
 */
class ImagePickerUtils {
  // 私有构造函数
  ImagePickerUtils._privateConstructor();

  // 单例实例
  static final ImagePickerUtils _instance = ImagePickerUtils._privateConstructor();

  // 获取单例实例的访问点
  factory ImagePickerUtils() {
    return _instance;
  }

  void show(
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) {
    SmartDialog.show(
        usePenetrate: false,
        alignment: Alignment.bottomCenter,
        builder: (context) => AlbumDefaultSelectDialog(
                //相机的选项
                cameraAction: () async {
              PermissionStatus cameraStatus = await Permission.camera.status;
              if (cameraStatus.isGranted) {
                //如果同意协议
                selectFormCamera(Get.context!, (filePath) {
                  complete(filePath);
                }, isCropped: isCropped, aspect: aspect);
              } else {
                //同时弹窗说明
                _showPermissionDialog("“Room”申请调用您的相机权限 用于使用拍摄头像，图片上传保存等功能，请允许我获取您的权限");
                var status = await Permission.camera.request();
                SmartDialog.dismiss(status: SmartStatus.dialog, tag: "permission");

                if (status.isGranted) {
                  selectFormCamera(Get.context!, (filePath) {
                    complete(filePath);
                  }, isCropped: isCropped, aspect: aspect);
                } else {
                  SmartDialog.show(builder: (context) {
                    return AppDefaultDialog("请到您的手机设置打开相机的权限", title: "提醒", confirmText: "去设置", confirmAction: () {
                      openAppSettings();
                    });
                  });
                }
              }
            }, albumAction: () async {
              //相册的选项
              if (Device.isIOS) {
                final value = await PhotoManager.requestPermissionExtend();
                if (value.hasAccess) {
                  //已授权
                  Log.d("相册已授权");
                  selectFormAlbum(Get.context!, (filePath) {
                    complete(filePath);
                  }, isCropped: isCropped, aspect: aspect);
                  return;
                } else if (value == PermissionState.limited) {
                  Log.d("相册访问受限，去设置");
                  PhotoManager.presentLimited();
                  return;
                } else {
                  Log.d("相册无权限，去设置");
                  SmartDialog.show(
                    usePenetrate: false,
                    keepSingle: true,
                    builder: (context) => AppDefaultDialog(
                      "无相册权限，前往设置".tr,
                      confirmAction: () {
                        PhotoManager.openSetting();
                      },
                    ),
                  );
                  return;
                }
              } else {
                //Android是否有SD卡权限
                PermissionStatus libStatus = await Permission.storage.status;
                if (libStatus.isGranted) {
                  //调用相册
                  Log.d("相册已授权");
                  selectFormAlbum(Get.context!, (filePath) {
                    complete(filePath);
                  }, isCropped: isCropped, aspect: aspect);
                } else {
                  //同时弹窗说明
                  _showPermissionDialog("“Room”想访问你的多媒体相册 用于图片上传，图片保存等功能，请允许我获取您的权限");
                  final PermissionState ps = await PhotoManager.requestPermissionExtend();
                  SmartDialog.dismiss(status: SmartStatus.dialog, tag: "permission");

                  if (ps.isAuth) {
                    //调用相册
                    Log.d("相册已授权");
                    selectFormAlbum(Get.context!, (filePath) {
                      complete(filePath);
                    }, isCropped: isCropped, aspect: aspect);
                  } else {
                    Log.d("相册未授权");
                    SmartDialog.show(builder: (context) {
                      return AppDefaultDialog("请到您的手机设置打开相册的权限", title: "提醒", confirmText: "去设置", confirmAction: () {
                        openAppSettings();
                      });
                    });
                  }
                }
              }
            }));
  }

  /// 从相机中选择
  Future selectFormCamera(
    BuildContext context,
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) async {
    final AssetEntity? result = await CameraEngine.takePhoto(context);

    if (result != null) {
      final file = await result.file;
      final filePath = file?.path;

      if (filePath != null && isCropped == true) {
        final croppedPath = await ImageCropEngine.imageCrop(context, filePath, aspect: aspect);
        complete(croppedPath!);
      } else {
        complete(filePath!);
      }
    }
  }

  /// 从相册中选择
  Future selectFormAlbum(
    BuildContext context,
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) async {
    final List<AssetEntity>? result = await AlbumEngine.selectImage(context, maxAssets: 1);
    if (result != null && result.isNotEmpty) {
      final file = await result[0].file;
      final filePath = file?.path;

      if (filePath != null && isCropped == true) {
        final croppedPath = await ImageCropEngine.imageCrop(context, filePath, aspect: aspect);
        complete(croppedPath!);
      } else {
        complete(filePath!);
      }
    }
  }

  //顶部展示权限声明详情弹窗
  void _showPermissionDialog(String desc) {
    SmartDialog.show(
      useAnimation: false,
      clickMaskDismiss: false,
      backDismiss: true,
      keepSingle: false,
      bindPage: true,
      tag: "permission",
      maskColor: Colors.transparent,
      builder: (context) => PermissionDescDialog(desc),
    );
  }
}
